# coding=utf-8
import arcpy
import xlrd
import xlwt
import os

inpath = ur"D:\sde_copy\地理国情监测数据测试"
outpath = ur"D:\sde_copy\地理国情监测数据测试\target.gdb"

workspace = inpath
ds_name = "LcrDataset"
fc_name = "V_LCRA"


# 循环向下遍历文件，收集特定文件类型的文件（以xxx结尾）
def list_fold_with_tag(root_path, all_files, ext):
    if os.path.isdir(root_path):
        files = os.listdir(root_path)
        for temp_file in files:
            current = os.path.join(root_path, temp_file)
            if os.path.isdir(current) and str(temp_file).lower().endswith(ext):
                all_files.append(current)
            else:
                list_fold_with_tag(current, all_files, ext)
    return all_files


def find_gdbs():
    gdb_fold = []
    list_fold_with_tag(inpath, gdb_fold, ".gdb")
    return gdb_fold


def find_fc_from_ds():
    fc_fold_with_dir = []
    for current_gdb_with_path in find_gdbs():
        arcpy.env.workspace = current_gdb_with_path
        for currentDS in arcpy.ListDatasets():
            if currentDS == ds_name:
                fcs = arcpy.ListFeatureClasses(feature_dataset=currentDS)
                # print fcs
                for currentFC in fcs:
                    if currentFC == fc_name:
                        fc_fold_with_dir.append(os.path.join(arcpy.env.workspace, ds_name, currentFC))

    return fc_fold_with_dir


def count_all_fcs():
    num_of_fcs = 0
    fcs_with_path = find_fc_from_ds()
    for fc in fcs_with_path:
        current_fc_num = arcpy.GetCount_management(fc)[0]
        num_of_fcs = num_of_fcs + int(current_fc_num)
    return num_of_fcs


if __name__ == '__main__':

    fcs_with_path = find_fc_from_ds()

    for fc in fcs_with_path:
        arcpy.AddMessage(fc)
    print "\n共计：" + "\n%s" % len(find_gdbs()) + "个gdb" + "\n%s" % len(fcs_with_path) + "个要素类"
    print "\n%s" % len(fcs_with_path) + "个要素类条目总数为：" + "\n%s" % count_all_fcs()

    if not arcpy.Exists(outpath + "/%s" % fc_name):
        print("============Start Merging==============")
        arcpy.Merge_management(find_fc_from_ds(), outpath + "/%s" % fc_name)
        print ("finish")
    else:
        print "该合并文件已存在，不再重复执行操作"

    print "============check result==============="
    boolflg = int(arcpy.GetCount_management(outpath + "/%s" % fc_name)[0]) == count_all_fcs()
    print ("合并后条目总数是否与元数据总数相符？" + "\n" + "%s" % boolflg)
